package com.ccom.ccomstart.properties;

import com.ccom.ccomstart.encrypt.BasicTextEncryptor;
import com.ccom.ccomstart.encrypt.StrongTextEncryptor;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

/**
 * @auther jjzhang24
 * @date 2021年12月06日 20:20
 */
//@Configuration
//@Component
public class JasyptProperties {

    @Value(value = "${jasypt.encryptor.password}")
    private String password;
    @Value(value = "${jasypt.encryptor.algorithm}")
    private String algorithm;

    public void setPassword(String password) {
        this.password = password;
    }

    public void setAlgorithm(String algorithm) {
        this.algorithm = algorithm;
    }

    public String getPassword() {
        return password;
    }

    public String getAlgorithm() {
        return algorithm;
    }

    @Bean("jasyptStringEncryptor")
    public StringEncryptor stringEncryptor() {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(password);
        config.setAlgorithm(algorithm);
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName(null);
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        return encryptor;
    }

    public String decrypt(String encryptedMessage) {
        if (null != encryptedMessage && encryptedMessage.startsWith("ENC(") && encryptedMessage.endsWith(")")) {
            String message = encryptedMessage.substring(4, encryptedMessage.length() - 1);
            if (algorithm.equals("PBEWithMD5AndDES")) {
                BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
                // 加密所需的salt(盐)
                textEncryptor.setPassword(password);
                return textEncryptor.decrypt(message);
            }
            if (algorithm.equals("PBEWithMD5AndTripleDES")) {
                StrongTextEncryptor textEncryptor = new StrongTextEncryptor();
                // 加密所需的salt(盐)
                textEncryptor.setPassword(password);
                return textEncryptor.decrypt(message);
            }
        }
        return encryptedMessage;
    }
}
